package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.MySocket;
import com.dotstone.chipism.bean.MySocket.RecDataCallBackListener_TempHumity;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.listener.CallbackOnInfraredSended;
import com.dotstone.chipism.listener.IInfraredSeneder;
import com.dotstone.chipism.listener.InfraredSeneder;
import com.dotstone.chipism.util.ConvertUtil;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.KeyManager;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;
import com.tiqiaa.ircode.IInfraredFetcher;
import com.tiqiaa.ircode.impl.InfraredFetcher;
import com.tiqiaa.irdnasdk.IrDnaSdkHelper;
import com.tiqiaa.remote.IRemoteManager;
import com.tiqiaa.remote.entity.AirRemoteState;
import com.tiqiaa.remote.entity.AirTemp;
import com.tiqiaa.remote.entity.Infrared;
import com.tiqiaa.remote.entity.Key;
import com.tiqiaa.remote.entity.Remote;
import com.tiqiaa.remote.impl.RemoteManager;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class AddAirActivity2 extends BaseActivity implements CallbackOnInfraredSended {
	private LinearLayout mBackL;
	private TextView mStatusBar;
	private Button mPowerB;
	private boolean on;
	private TextView mTitleTv;
	private Button mVoiceB;
	private Button mModeB;
	// private ImageView m
	private Button mWindB;
	private Button mDerictionB;
	private Button mDerictionB1;
	private Button mWarmB;
	private Button mColdB;
	private Button mTimeB;
	private Button mMoreB;
	private RelativeLayout mF;
	private RelativeLayout mS;
	private Vibrator vibrator;
	private ImageView mShiImg;
	private ImageView mGeImg;
	private ImageView mModeImg;
	private int mode = 0; // 0 制冷 1 制暖 2 干燥
	private MySocket socket;
	private int inner;
	private Button mSaveB;
	private int type;
	private String aplliance;
	private String brand;
	private String model;
	private String remoteId;
	// private List<com.dotstone.chipism.bean.Key> moreKeys = new
	// ArrayList<com.dotstone.chipism.bean.Key>();
	private Dialog dialog;
	private GridView mKeysG;
	private KeyAdapter mAdapter;
	private SVProgressHUD mSVProgressHUD;
	private static int dpi;
	private int o_x = 300;
	private int o_y = 302;
	private Remote remote;
	private float current_degree;
	private int tempX1;
	private int tempY1;
	private int temp;
	private int temp1;
	private List<Button> buttons = new ArrayList<Button>();
	private List<Key> moreKeys = new ArrayList<Key>();
	private IInfraredSeneder mSeneder;
	private CallbackOnInfraredSended mCallbackOnInfraredSended;
	private TextView wendu_tv;
	private TextView shidu_tv;
	private String wendu;
	private String shidu;
	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		case R.id.power_b:
			sendCmd(800);
			break;
		case R.id.voice_btn:
			ToastShow.Show(getApplicationContext(), "尚未实现");
			break;
		case R.id.mode_btn:
			// 832
			Log.i("wmy", "141点击了模式");
			sendCmd(832);
			vibrator.vibrate(50);
			break;
		case R.id.wind_speed_btn:
			// 833
			sendCmd(833);
			vibrator.vibrate(50);
			break;
		case R.id.wind_deriction_btn:
			// 834 左右扫风
			sendCmd(834);
			vibrator.vibrate(50);
			break;
		case R.id.wind_deriction_btn1:
			// 835 上下扫风
			sendCmd(835);
			vibrator.vibrate(50);
			break;
		case R.id.warn_btn:
			// 883
			sendCmd(883);
			mModeImg.setImageResource(R.drawable.hot);
			vibrator.vibrate(50);
			break;
		case R.id.cold_btn:
			// 882
			sendCmd(882);
			mModeImg.setImageResource(R.drawable.cold);
			vibrator.vibrate(50);
			break;
		case R.id.time_btn:
			// 876
			sendCmd(876);
			vibrator.vibrate(50);
			break;
		case R.id.more_btn:
			initDialog();
			break;
		case R.id.nextstep:
			save();
			break;
		default:
			break;
		}
	}

	private void sendCmd(int id) {
		Key key = null;
		for (int i = 0; i < remote.getKeys().size(); i++) {
			Log.e("wmy", remote.getKeys().get(i).getType() + " 获取了 " + remote.getKeys().get(i).getLocalName() + "按键");
			if (remote.getKeys().get(i).getType() == id) {
				key = remote.getKeys().get(i);
				Log.e("wmy", "获取了" + key.getLocalName() + "按键");
			}
		}
		if (key != null) {
			mSeneder.send(remote, key);
			mCallbackOnInfraredSended.onInfrardSended();
			vibrator.vibrate(50);
		}
	}

	private String getCmd(int id) {
		Key key = null;
		String cmd = null;
		for (int i = 0; i < remote.getKeys().size(); i++) {
			Log.e("wmy", remote.getKeys().get(i).getType() + " 获取了 " + remote.getKeys().get(i).getLocalName() + "按键");
			if (remote.getKeys().get(i).getType() == id) {
				key = remote.getKeys().get(i);
				Log.e("wmy", "获取了" + key.getLocalName() + "按键");
			}
		}
		if (key != null) {
			mSeneder.send(remote, key);
			mCallbackOnInfraredSended.onInfrardSended();
			vibrator.vibrate(50);
		}
		return cmd;
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				int[] temps = new int[2];
				temps = Util.getTempRes(msg.arg1);
				mShiImg.setImageResource(temps[0]);
				mGeImg.setImageResource(temps[1]);
				if (msg.arg2 == 0) {
					mModeImg.setImageResource(R.drawable.auto);
				} else if (msg.arg2 == 1) {
					mModeImg.setImageResource(R.drawable.hot);
				} else if (msg.arg2 == 2) {
					mModeImg.setImageResource(R.drawable.cold);
				} else if (msg.arg2 == 3) {
					mModeImg.setImageResource(R.drawable.dry);
				}
				break;
			case 1:
				wendu = socket.getTemp() + "";
				shidu = socket.getHumity() + "";
				wendu_tv.setText("当前温度：\n" + wendu + "℃");
				shidu_tv.setText("当前湿度：\n" + shidu);
				break;
			default:
				break;
			}
		}
	};

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_air;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		dpi = DeviceManager.getInstance().getDEVICE_DENSITY_DPI();
		o_x = 309 * dpi / 320;
		o_y = 309 * dpi / 320;
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mTitleTv = $(R.id.title_tv);
		mPowerB = $(R.id.power_b);
		mVoiceB = $(R.id.voice_btn);
		mModeB = $(R.id.mode_btn);
		mWindB = $(R.id.wind_speed_btn);
		mDerictionB = $(R.id.wind_deriction_btn);
		mDerictionB1 = $(R.id.wind_deriction_btn1);
		mWarmB = $(R.id.warn_btn);
		mColdB = $(R.id.cold_btn);
		mTimeB = $(R.id.time_btn);
		mMoreB = $(R.id.more_btn);
		mShiImg = $(R.id.shi_img);
		mGeImg = $(R.id.ge_img);
		mModeImg = $(R.id.mode_img);
		wendu_tv = $(R.id.wendu);
		shidu_tv = $(R.id.shidu);
		mF = (RelativeLayout) findViewById(R.id.rl_father);
		mS = (RelativeLayout) findViewById(R.id.rl_mezi);
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		mSaveB = $(R.id.nextstep);
		mSaveB.setText(getString(R.string.save));
		type = getIntent().getIntExtra("type", 999);
		aplliance = getIntent().getStringExtra("appliance");
		brand = getIntent().getStringExtra("brand");
		model = getIntent().getStringExtra("model");
		remoteId = getIntent().getStringExtra("remoteId");
		mTitleTv.setText(aplliance + " " + brand + " " + model);
		socket = SocketManager.getInstance().sMap.get(DeviceManager.getInstance().getmWlanId());
		mSeneder = new InfraredSeneder(getApplicationContext());
		initButtons();
		if (socket == null) {
			ToastShow.Show(getApplicationContext(), "请重新选择网关再添加！");
			// return;
			finish();
		}
		mSaveB.setVisibility(View.VISIBLE);
		IRemoteManager manager = new RemoteManager();
		remote = manager.getRemoteByID(remoteId);
		showAirState();
		initMoreKey();
		initTestKey();// 测试用
		checkCurrentState();
		boolVersion();
		mBackL.setOnClickListener(this);
		mPowerB.setOnClickListener(this);
		mVoiceB.setOnClickListener(this);
		mModeB.setOnClickListener(this);
		mWindB.setOnClickListener(this);
		mDerictionB.setOnClickListener(this);
		mDerictionB1.setOnClickListener(this);
		mWarmB.setOnClickListener(this);
		mColdB.setOnClickListener(this);
		mTimeB.setOnClickListener(this);
		mMoreB.setOnClickListener(this);
		mSaveB.setOnClickListener(this);
		mCallbackOnInfraredSended = new CallbackOnInfraredSended() {

			@Override
			public void onInfrardSended() {
				// TODO Auto-generated method stub
				showAirState();
			}
		};
		socket = SocketManager.getInstance().sMap.get(DeviceManager.getInstance().getmWlanId());
		if (socket != null) {
			setRecall();
			// initTemp();
		}
		mF.setOnTouchListener(new OnTouchListener() {
			// 根据角度 判断区域属于哪一个温度
			// 如果属于同一个温度 则不做处理
			// 如果属于不同温度 则赋值当前温度
			// 震动
			@Override
			public boolean onTouch(View v, MotionEvent e) {
				// TODO Auto-generated method stub
				int action = e.getAction();
				switch (action) {
				case MotionEvent.ACTION_DOWN:

					break;
				case MotionEvent.ACTION_MOVE:
					// Log.i("wmy", "拖动" + e.getX() + " " + e.getY());
					if (on) {
						if (adjustArea(o_x, o_y, e.getX(), e.getY())) {
							current_degree = detaDegree(o_x, o_y, e.getX(), e.getY());
							// 根据象限求坐标
							if (current_degree < 50 || current_degree > 130) {
								// if (currentTime - lastTime > 150) {
								// lastTime = currentTime;
								// adjustTemp(current_degree);
								// }
								getButtonXY(current_degree);
								mS.setX(tempX1 - 24 * dpi / 320);
								mS.setY(tempY1 - 24 * dpi / 320);
								mS.postInvalidate();
							}
						} else {
							return false;
						}
					}
					break;
				case MotionEvent.ACTION_UP:
					// Log.i("wmy", "上提" + e.getX() + " " + e.getY());
					if (on) {
						if (adjustArea(o_x, o_y, e.getX(), e.getY())) {
							current_degree = detaDegree(o_x, o_y, e.getX(), e.getY());
							// 根据象限求坐标
							if (current_degree < 50 || current_degree > 130) {
								Log.i("wmy", "当前上提角度" + current_degree);
								adjustTemp(current_degree);
								getButtonXY(current_degree);
								mS.setX(tempX1 - 20 * dpi / 320);
								mS.setY(tempY1 - 20 * dpi / 320);
								mS.postInvalidate();
							}
						} else {
							return false;
						}
					}
					break;

				default:
					break;
				}
				return true;
			}
		});
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		DeviceManager.getInstance().setNeedToCheckTemp(true);
	}
	
	private void checkCurrentState() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (true) {
					try {
						Thread.sleep(2000);
						mHandler.sendEmptyMessage(1);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	private boolean adjustArea(float src_x, float src_y, float target_x, float target_y) {
		inner = (int) Math.sqrt(Math.pow(Math.abs(target_x - src_x), 2) + Math.pow(Math.abs(target_y - src_y), 2));
		if (inner < 300 * dpi / 320 && inner > 90 * dpi / 320) {
			return true;
		} else {
			return false;
		}
	}

	float detaDegree(float src_x, float src_y, float target_x, float target_y) {
		float detaX = target_x - src_x;
		float detaY = target_y - src_y;
		double d;
		if (detaX != 0) {
			float tan = Math.abs(detaY / detaX);

			if (detaX > 0) {

				if (detaY >= 0) {
					d = Math.atan(tan);

				} else {
					d = 2 * Math.PI - Math.atan(tan);
				}

			} else {
				if (detaY >= 0) {

					d = Math.PI - Math.atan(tan);
				} else {
					d = Math.PI + Math.atan(tan);
				}
			}

		} else {
			if (detaY > 0) {
				d = Math.PI / 2;
			} else {

				d = -Math.PI / 2;
			}
		}
		return (float) ((d * 180) / Math.PI);
	}

	private void getButtonXY(float degree) {
		tempX1 = (int) (o_x + (150 * dpi / 320 * Math.cos(Math.toRadians(degree))));
		tempY1 = (int) (o_y + (150 * dpi / 320 * Math.sin(Math.toRadians(degree))));
	}

	private void adjustTemp(float degree) {
		if (130 < degree && degree <= 160) {
			if (temp != 16) {
				temp = 16;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd();
				showAirState();
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_1);
				mGeImg.setImageResource(R.drawable.ac_6);
				vibrator.vibrate(50);
			}
		} else if (160 < degree && degree <= 177) {
			if (temp != 17) {
				temp = 17;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd();
				showAirState();
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_1);
				mGeImg.setImageResource(R.drawable.ac_7);
				vibrator.vibrate(50);
			}
		} else if (177 < degree && degree <= 194) {
			if (temp != 18) {
				temp = 18;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd();
				showAirState();
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_1);
				mGeImg.setImageResource(R.drawable.ac_8);
				vibrator.vibrate(50);
			}
		} else if (194 < degree && degree <= 211) {
			if (temp != 19) {
				temp = 19;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd();
				showAirState();
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_1);
				mGeImg.setImageResource(R.drawable.ac_9);
				vibrator.vibrate(50);
			}
		} else if (211 < degree && degree <= 228) {
			if (temp != 20) {
				temp = 20;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd();
				showAirState();
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_0);
				vibrator.vibrate(50);
			}
		} else if (228 < degree && degree <= 245) {
			if (temp != 21) {
				temp = 21;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd();
				showAirState();
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_1);
				vibrator.vibrate(50);
			}
		} else if (245 < degree && degree <= 262) {
			if (temp != 22) {
				temp = 22;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd();
				showAirState();
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_2);
				vibrator.vibrate(50);
			}
		} else if (262 < degree && degree <= 279) {
			if (temp != 23) {
				temp = 23;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd();
				showAirState();
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_3);
				vibrator.vibrate(50);
			}
		} else if (279 < degree && degree <= 296) {
			if (temp != 24) {
				temp = 24;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd();
				showAirState();
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_4);
				vibrator.vibrate(50);
			}
		} else if (296 < degree && degree <= 313) {
			if (temp != 25) {
				temp = 25;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd();
				showAirState();
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_5);
				vibrator.vibrate(50);
			}
		} else if (313 < degree && degree <= 330) {
			if (temp != 26) {
				temp = 26;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd();
				showAirState();
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_6);
				vibrator.vibrate(50);
			}
		} else if (330 < degree && degree <= 347) {
			if (temp != 27) {
				temp = 27;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd();
				showAirState();
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_7);
				vibrator.vibrate(50);
			}
		} else if (347 < degree || degree <= 3) {
			if (temp != 28) {
				temp = 28;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd();
				showAirState();
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_8);
				vibrator.vibrate(50);
			}
		} else if (3 < degree && degree <= 20) {
			if (temp != 29) {
				temp = 29;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd();
				showAirState();
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_2);
				mGeImg.setImageResource(R.drawable.ac_9);
				vibrator.vibrate(50);
			}
		} else if (20 < degree && degree <= 50) {
			if (temp != 30) {
				temp = 30;
				if (temp1 > temp) {
					Log.i("wmy", "调低温度");
					// sendCmdThread(false, temp1 - temp);
				} else {
					Log.i("wmy", "调高温度");
					// sendCmdThread(true, temp - temp1);
				}
				sendCmd();
				showAirState();
				temp1 = temp;
				mShiImg.setImageResource(R.drawable.ac_3);
				mGeImg.setImageResource(R.drawable.ac_0);
				vibrator.vibrate(50);
			}
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	private void initButtons() {
		buttons.add(mModeB);
		buttons.add(mWindB);
		buttons.add(mDerictionB);
		buttons.add(mDerictionB1);
		buttons.add(mWarmB);
		buttons.add(mColdB);
		buttons.add(mTimeB);
		buttons.add(mMoreB);
	}

	private void initMoreKey() {
		// 在遥控器主面板已有的按键 832 833 834 835 883 882 876 800
		for (int i = 0; i < remote.getKeys().size(); i++) {
			if (remote.getKeys().get(i).getType() != 800 && remote.getKeys().get(i).getType() != 834
					&& remote.getKeys().get(i).getType() != 832 && remote.getKeys().get(i).getType() != 833
					&& remote.getKeys().get(i).getType() != 835 && remote.getKeys().get(i).getType() != 883
					&& remote.getKeys().get(i).getType() != 882 && remote.getKeys().get(i).getType() != 876) {
				moreKeys.add(remote.getKeys().get(i));
			}
		}
	}

	private void initTestKey() {
		// 获取电源
		InfraredFetcher mFetcher = new InfraredFetcher(getApplicationContext());
		AirRemoteState mState = mFetcher.getAirRemoteStatus(remote);
	}

	private void sendCmd() {
		InfraredFetcher mFetcher = new InfraredFetcher(getApplicationContext());
		AirRemoteState mState = mFetcher.getAirRemoteStatus(remote);
		List<Infrared> irList = mFetcher.fetchAirInfrareds(remote, mState, mState.getPower(), mState.getMode(),
				mState.getWind_amount(), AirTemp.getAirTemp(temp));
		Log.i("wmy", "根据度数 " + temp + " 获取指令 = " + irList.size());
		for (int i = 0; i < irList.size(); i++) {
			if (irList.get(i) != null && irList.get(i).getData() != null) {
				byte[] data = IrDnaSdkHelper.getIrCode(irList.get(i).getFreq(), irList.get(i).getData());
				String str = Util.bytesToHexString(data).toUpperCase();
				String cmd = ConvertUtil.getInstance().convertInfraredCmd(str);
				// Log.e("wmy", "空调....###..解析出的红外数据..data = " + cmd);
				socket.sendMqttData(cmd);
			}
		}
	}

	private void setRecall() {
		socket.setRecDataCallBackListener_TempHumity(new RecDataCallBackListener_TempHumity() {

			@Override
			public void onReceiveData(String data) {
				// TODO Auto-generated method stub
				parseData(data);
			}
		});
	}

	private void parseData(String data) {
		try {
			JSONObject jo = new JSONObject(data);
			String g = jo.getString("g");
			JSONObject jo1 = new JSONObject(g);
			int temperature = (int) jo1.getDouble("temperature");
			Message msg = Message.obtain();
			msg.what = 0;
			msg.arg1 = temperature;
			mHandler.sendMessage(msg);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initDialog() {
		// TODO Auto-generated method stub
		dialog = new Dialog(AddAirActivity2.this, R.style.MyDialogStyle);
		dialog.setContentView(R.layout.dialog_more_key);
		Window dialogWindow = dialog.getWindow();
		mKeysG = (GridView) dialog.findViewById(R.id.key_gv);
		mAdapter = new KeyAdapter();
		mKeysG.setAdapter(mAdapter);
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.setGravity(Gravity.CENTER);
		lp.width = LayoutParams.FILL_PARENT;
		dialogWindow.setAttributes(lp);
		dialog.show();
	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	private void showAirState() {
		// 获取状态z
		IInfraredFetcher mFetcher = new InfraredFetcher(this);
		AirRemoteState state = mFetcher.getAirRemoteStatus(remote);
		Log.i("wmy",
				"showAirState......##......state.power = " + state.getPower() + " , state.mode = " + state.getMode()
						+ " , state.temp=" + state.getTemp() + " , state.wind_amount = " + state.getWind_amount());
		// initTemp = state.getTemp().value();
		switch (state.getPower()) {
		case POWER_ON:
			on = true;
			resetButtons(true);
			break;

		default:
			on = false;
			resetButtons(false);
			break;
		}
		switch (state.getTemp().value()) {
		case 16:
			mShiImg.setImageResource(R.drawable.ac_1);
			mGeImg.setImageResource(R.drawable.ac_6);
			break;
		case 17:
			mShiImg.setImageResource(R.drawable.ac_1);
			mGeImg.setImageResource(R.drawable.ac_7);
			break;
		case 18:
			mShiImg.setImageResource(R.drawable.ac_1);
			mGeImg.setImageResource(R.drawable.ac_8);
			break;
		case 19:
			mShiImg.setImageResource(R.drawable.ac_1);
			mGeImg.setImageResource(R.drawable.ac_9);
			break;
		case 20:
			mShiImg.setImageResource(R.drawable.ac_2);
			mGeImg.setImageResource(R.drawable.ac_0);
			break;
		case 21:
			mShiImg.setImageResource(R.drawable.ac_2);
			mGeImg.setImageResource(R.drawable.ac_1);
			break;
		case 22:
			mShiImg.setImageResource(R.drawable.ac_2);
			mGeImg.setImageResource(R.drawable.ac_2);
			break;
		case 23:
			mShiImg.setImageResource(R.drawable.ac_2);
			mGeImg.setImageResource(R.drawable.ac_3);
			break;
		case 24:
			mShiImg.setImageResource(R.drawable.ac_2);
			mGeImg.setImageResource(R.drawable.ac_4);
			break;
		case 25:
			mShiImg.setImageResource(R.drawable.ac_2);
			mGeImg.setImageResource(R.drawable.ac_5);
			break;
		case 26:
			mShiImg.setImageResource(R.drawable.ac_2);
			mGeImg.setImageResource(R.drawable.ac_6);
			break;
		case 27:
			mShiImg.setImageResource(R.drawable.ac_2);
			mGeImg.setImageResource(R.drawable.ac_7);
			break;
		case 28:
			mShiImg.setImageResource(R.drawable.ac_2);
			mGeImg.setImageResource(R.drawable.ac_8);
			break;
		case 29:
			mShiImg.setImageResource(R.drawable.ac_2);
			mGeImg.setImageResource(R.drawable.ac_9);
			break;
		case 30:
			mShiImg.setImageResource(R.drawable.ac_3);
			mGeImg.setImageResource(R.drawable.ac_0);
			break;
		case 31:
			mShiImg.setImageResource(R.drawable.ac_3);
			mGeImg.setImageResource(R.drawable.ac_1);
			break;
		case 32:
			mShiImg.setImageResource(R.drawable.ac_3);
			mGeImg.setImageResource(R.drawable.ac_2);
			break;
		default:
			break;
		}

		switch (state.getMode()) {
		case WIND:
			mModeImg.setImageResource(R.drawable.quick_songfeng);
			break;

		case COOL:
			mModeImg.setImageResource(R.drawable.cold);
			break;
		case HOT:
			mModeImg.setImageResource(R.drawable.hot);
			break;

		case DRY:
			mModeImg.setImageResource(R.drawable.dry);
			break;

		default:
			mModeImg.setImageResource(R.drawable.auto);
			break;
		}

		switch (state.getWind_amount()) {
		case LEVEL_1:
			mWindB.setText("一档");
			break;
		case LEVEL_2:
			mWindB.setText("二档");
			break;
		case LEVEL_3:
			mWindB.setText("三档");
			break;
		case LEVEL_4:
			mWindB.setText("四档");
			break;
		default:
			mWindB.setText("自动");
			break;
		}
	}

	private void resetButtons(boolean on) {
		// for(int i = 0;i<buttons.size();i++){
		//
		// }
		if (on) {
			mModeB.setEnabled(true);
			mModeB.setBackgroundResource(R.drawable.selector_mode);
			mWindB.setEnabled(true);
			mWindB.setTextColor(Color.parseColor("#3fb6d5"));
			mWindB.setBackgroundResource(R.drawable.kuang2x);
			mDerictionB.setEnabled(true);
			mDerictionB.setBackgroundResource(R.drawable.selector_deriction);
			mDerictionB1.setEnabled(true);
			mDerictionB1.setBackgroundResource(R.drawable.selector_deriction1);
			mWarmB.setEnabled(true);
			mWarmB.setBackgroundResource(R.drawable.selector_warm);
			mColdB.setEnabled(true);
			mColdB.setBackgroundResource(R.drawable.selector_cold);
			mTimeB.setEnabled(true);
			mTimeB.setBackgroundResource(R.drawable.selector_time);
		} else {
			mModeB.setBackgroundResource(R.drawable.moshi1x);
			mModeB.setEnabled(false);
			mWindB.setBackgroundResource(R.drawable.kuang2x);
			mWindB.setTextColor(Color.parseColor("#b9b9b9"));
			mWindB.setEnabled(false);
			mDerictionB.setBackgroundResource(R.drawable.xiabai12x);
			mDerictionB.setEnabled(false);
			mDerictionB1.setBackgroundResource(R.drawable.shangbai12x);
			mDerictionB1.setEnabled(false);
			mWarmB.setBackgroundResource(R.drawable.zhire12x);
			mWarmB.setEnabled(false);
			mColdB.setBackgroundResource(R.drawable.zhileng12x);
			mColdB.setEnabled(false);
			mTimeB.setBackgroundResource(R.drawable.naozhong12x);
			mTimeB.setEnabled(false);
		}
	}

	private void save() {
		mSVProgressHUD = new SVProgressHUD(AddAirActivity2.this);
		mSVProgressHUD.showWithStatus("正在保存");
		// 上传设备
		RequestParams params = new RequestParams(HttpURL.UPLOAD_DEVICE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {

			obj.put("classification", "4");
			obj.put("key", "10000");
			obj.put("deviceModel", remoteId);
			obj.put("deviceName", aplliance + " " + brand + " " + model);
			obj.put("deviceType", type + "");
			obj.put("deviceVersion", "3.1.0");
			obj.put("deviceWifiSSID", remoteId.equals("") ? "未知" : remoteId);
			obj.put("deviceId", "0");
			obj.put("productId", "4");
			obj.put("mainDeviceId", DeviceManager.getInstance().getmWlanId());
			obj.put("hid", DeviceManager.getInstance().hid);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.d("test", " upload obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("test", "upload=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String value = jsonObject.getString("resultCode");
					if (value.equals("1")) {
						String deviceId = jsonObject.getString("data");
						// 获取deviceId之后 上传所有按键
//						 uploadKeys(deviceId);
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						ToastShow.Show(getApplicationContext(), "保存成功！");
						finish();
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), "保存失败：" + errorMsg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}
	
//	private void uploadKeys(String deviceId) {
//		// 上传按键
//		String buttonCmdS = "";
//		String positionS = "";
//		String nameS = "";
//		boolean e = false;
//		String cmd = "";
//		List<Key> keys = remote.getKeys();
//		for (int i = 0; i < keys.size(); i++) {
//			if (cmdMaps.get(keys.get(i).getType()) != null) {
//				buttonCmdS += irDataMaps.get(keys.get(i).getType()) + ",";
//				positionS += keys.get(i).getType() + ",";
//				if (keys.get(i).getType() == 800) {
//					nameS += "打开" + ",";
//					cmd = irDataMaps.get(keys.get(i).getType());
//				} else if (keys.get(i).getType() == 4000) {
//					e = true;
//					nameS += "关闭" + ",";
//				} else {
//					nameS += keys.get(i).getLocalName() + ",";
//				}
//			}
//		}
//		if (!e) {
//			buttonCmdS += cmd+",";
//			nameS += "关闭" + ",";
//			positionS += 4000 + ",";
//		}
//
//		for (int i = 0; i < tempKeys.size(); i++) {
//			buttonCmdS += irDataMaps.get(tempKeys.get(i).getKeyNum()) + ",";
//			positionS += tempKeys.get(i).getKeyNum() + ",";
//			nameS += KeyManager.getInstance().getKeyNameById(tempKeys.get(i).getKeyNum()) + ",";
//		}
//		if (buttonCmdS.length() > 1) {
//			buttonCmdS = buttonCmdS.substring(0, buttonCmdS.length() - 1);
//		}
//		if (positionS.length() > 1) {
//			positionS = positionS.substring(0, positionS.length() - 1);
//		}
//		if (nameS.length() > 1) {
//			nameS = nameS.substring(0, nameS.length() - 1);
//		}
//		RequestParams params = new RequestParams(HttpURL.UPLOAD_REMOTE_KEY_URL);
//		params.setAsJsonContent(true);
//		JSONObject obj = new JSONObject();
//		try {
//			obj.put("buttonCmdS", buttonCmdS);
//			obj.put("key", "10000");
//			obj.put("positionS", positionS);
//			obj.put("nameS", nameS);
//			obj.put("deviceId", deviceId);
//			obj.put("requestTime", "" + System.currentTimeMillis());
//			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
//			Log.d("test", " upload obj = " + obj.toString());
//		} catch (JSONException e1) {
//			e1.printStackTrace();
//		}
//		params.setBodyContent(obj.toString());
//		x.http().post(params, new Callback.CommonCallback<String>() {
//			@Override
//			public void onSuccess(String result) {
//				Log.e("test", "upload=" + result);
//				try {
//					JSONObject jsonObject = new JSONObject(result);
//					String value = jsonObject.getString("resultCode");
//					if (value.equals("1")) {
//						if (mSVProgressHUD.isShowing()) {
//							mSVProgressHUD.dismiss();
//						}
//						ToastShow.Show(getApplicationContext(), "保存成功");
//						finish();
//					} else {
//						if (mSVProgressHUD.isShowing()) {
//							mSVProgressHUD.dismiss();
//						}
//						String errorMsg = jsonObject.getString("errorMsg");
//						ToastShow.Show(getApplicationContext(), "保存失败：" + errorMsg);
//					}
//				} catch (JSONException e) {
//					e.printStackTrace();
//				}
//			}
//
//			@Override
//			public void onCancelled(CancelledException arg0) {
//
//			}
//
//			@Override
//			public void onError(Throwable arg0, boolean arg1) {
//
//			}
//
//			@Override
//			public void onFinished() {
//
//			}
//
//		});
//	}

	class KeyAdapter extends BaseAdapter {
		HoldView holdView;
		private int imageResId;
		private int stringResId;

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return moreKeys.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return moreKeys.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View v, ViewGroup parent) {
			// TODO Auto-generated method stub
			if (v == null) {
				v = LayoutInflater.from(AddAirActivity2.this).inflate(R.layout.item_more_key, null);
				holdView = new HoldView();
				holdView.btn = (Button) v.findViewById(R.id.key_btn);
				v.setTag(holdView);
			} else {
				holdView = (HoldView) v.getTag();
			}
			final Key k = moreKeys.get(position);
			holdView.btn.setTag(k.getType());
			int content = KeyManager.getInstance().getContentTypeByKeyNum(k.getType());
			if (content == 0) {
				imageResId = KeyManager.getInstance().getDrawableResId(k.getType());
				holdView.btn.setBackgroundResource(imageResId);
			} else {
				stringResId = KeyManager.getInstance().getStringResId(k.getType());
				holdView.btn.setText(stringResId);
			}
			holdView.btn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Log.i("wmy", "点击了" + k.getType() + " " + k.getLocalName());
					int tag = Integer.parseInt(v.getTag().toString());
					sendCmd(tag);
					vibrator.vibrate(50);
				}
			});

			return v;
		}
	}

	class HoldView {
		private Button btn;
	}

	@Override
	public void onInfrardSended() {
		// TODO Auto-generated method stub
		// 如果是空调遥控器，则刷新状态屏
		showAirState();

	}
}
